package com.dmgis.qxfw.dataservice.commonservice.dmgis_pg_srv.controller;


import com.dmgis.qxfw.dataservice.commonservice.common.DESUtil;
import com.dmgis.qxfw.dataservice.commonservice.dmgis_pg_srv.common.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.commonservice.utils.PGUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author lw
 * @ClassName: ProcessRequestController
 * @date 2018年9月10日 下午2:02:16
 * @Description:
 */
@Controller
@RequestMapping("/dataservice")
public class ProcessRequestController {

    @RequestMapping("/pgDataService")
    @ResponseBody
    public String processRequest(HttpServletRequest request, HttpServletResponse response)  {
        String tableName="",sqlType="",advCode="",param="";
        Map<String, String[]> params=request.getParameterMap();
        if (params.size() == 4) {
            tableName =request.getParameter("method");
            sqlType = request.getParameter("sqlType");
            param = request.getParameter("param");
            advCode = request.getParameter("advCode");
        } else  if (params.size() > 0) {
            try {
                String data = request.getParameter("data");
                String paramlist = DESUtil.decrypt(data, "ABCQiS88");
                //data = new String(bdata);
                String[] list = paramlist.split("&");
                for (String str : list
                ) {
                    if(str.contains("=")) {
                        int index=str.indexOf("=");
                        String key = str.substring(0,index);
                        String value = str.substring(index+1);
                        if (key.equals("method"))
                            tableName = value;
                        else if (key.equals("sqlType"))
                            sqlType = value;
                        else if (key.equals("param"))
                            param = value;
                        else if (key.equals("advCode"))
                            advCode = value;
                    }
                }
            }
            catch (Exception e){return "传入数据异常！";}
        }
        else
        {
            return "传入数据为空！";
        }


        String result;
        String sql;
        // 根据url选择数据库
        String dataBaseName = DbConfig.DBNAME;
        if (advCode != null && advCode.length() != 0) {
            dataBaseName = DbConfig.DBNAME + "service_data_" + advCode;
        } else {
            dataBaseName = DbConfig.DBNAME + "qx_data";
        }
        if (tableName == null || "".equals(tableName) || tableName.isEmpty()) {
            return "method不能为空！";
        }
        if ("".equals(sqlType) || sqlType == null || sqlType.isEmpty()) {
            return "sqlType不能为空！";
        }
        tableName = tableName.trim();
        Handle handle = new Handle();
        try {
            //判断表是否存在,暂时判断，因为有视图
            // 查询
            if ("select".equals(sqlType.trim().toLowerCase())) {
                // 拼接sql语句
                sql = handle.getData(param, tableName);
                // 查询数据,直接返回JSON数据
                //比返回map要快一点
                result = PGUtil.getResultSetJsonString(DbConfig.pg_url + dataBaseName, DbConfig.pg_userName, DbConfig.pg_pwd, sql);//json;
                if (result.startsWith("[")) { //成功
                    //getTableCallCount(dataBaseName, tableName, "select", sql, true);
                } else   {
                    //getTableCallCount(dataBaseName, tableName, "select", sql, false);
                }
                return result;
            }
            // 删除
            if ("delete".equals(sqlType.trim().toLowerCase())) {
                sql = handle.delData(param, tableName);
                if (sql.length() > 0) {
                    int count = PGUtil.ExecuteNoQueryWithoutReturning(DbConfig.pg_url + dataBaseName, DbConfig.pg_userName, DbConfig.pg_pwd, sql);
                    getTableCallCount(dataBaseName, tableName, "delete", sql, count >= 0 ? true : false);
                    return String.valueOf(count);
                }
            }
            // 更新
            if ("update".equals(sqlType.trim().toLowerCase())) {
                sql = handle.updateData(param, tableName);
                if (sql.length() > 0) {
                    int count = PGUtil.ExecuteNoQueryWithoutReturning(DbConfig.pg_url + dataBaseName, DbConfig.pg_userName, DbConfig.pg_pwd, sql);
                    //getTableCallCount(dataBaseName, tableName, "update", sql, count >= 0 ? true : false);
                    return String.valueOf(count);
                }
            }
            //更新多条数据
            if ("updates".equals(sqlType.trim().toLowerCase())) {
                sql = handle.updatesData(param, tableName);
                if (sql.length() > 0) {
                    int count = PGUtil.ExecuteNoQueryWithoutReturning(DbConfig.pg_url + dataBaseName, DbConfig.pg_userName, DbConfig.pg_pwd, sql);
                    //getTableCallCount(dataBaseName, tableName, "updates", sql, count >= 0 ? true : false);
                    return String.valueOf(count);
                }
            }
            // TODO 插入
            if ("insert".equals(sqlType.trim().toLowerCase())) {
                String[] res = handle.insertData(param, tableName);
                sql = res[0];
                String isReturning = res[1];
                if (sql.length() > 0) {
                    int count;
                    if (!StringUtil.IsNullOrEmpty(isReturning) && isReturning.equals("1"))
                        count = PGUtil.ExecuteNoQuery(DbConfig.pg_url + dataBaseName, DbConfig.pg_userName, DbConfig.pg_pwd, sql);
                    else
                        count = PGUtil.ExecuteNoQueryWithoutReturning(DbConfig.pg_url + dataBaseName, DbConfig.pg_userName, DbConfig.pg_pwd, sql);
                    //getTableCallCount(dataBaseName, tableName, "insert", sql, count >= 0 ? true : false);
                    return String.valueOf(count);
                }
            }

        } catch (Exception e) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(bos));
            String exception = bos.toString();
            return "（数据操作异常）" + exception;
        }
        return "请求响应结束,原因未知！";
    }


    private boolean getTableCallCount(String dbName, String tableName, String operate, String operateSql, boolean success) {
        //操作状态
        boolean flag = false;
        String nowDate = DateTime.now().toDateTimeString("yyyy-MM-dd HH:00:00");
        try {
            //判断是否存在
            String strWhere = String.format("where datetime='%s' and databasename='%s'and tablename='%s' and operatetype='%s'",
                    nowDate, dbName, tableName, operate);
            String strSql = String.format("select callcount,errcallcount from table_call_count " + strWhere);
            ArrayList<Map<String, Object>> list = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.DBNAME + "qx_data", DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
            StringBuilder strSqlBuilder = new StringBuilder();
            int callcount = 0;
            int errcallcount = 0;
            operateSql = operateSql.replace("'", "\''");
            if (list.size() > 0)  //更新
            {
                callcount = Integer.parseInt(list.get(0).get("callcount").toString());
                errcallcount = Integer.parseInt(list.get(0).get("errcallcount").toString());
                strSqlBuilder.append("update table_call_count set ");
                if (success)    //成功
                {
                    strSqlBuilder.append("callcount= " + (callcount + 1));
                } else {
                    strSqlBuilder.append("errcallcount= " + (errcallcount + 1));
                    strSqlBuilder.append(" operatesql='" + operateSql + "'");
                }
                strSqlBuilder.append(strWhere);
            } else    //插入
            {
                if (success) {
                    callcount = 1;
                    errcallcount = 0;
                } else {
                    callcount = 0;
                    errcallcount = 1;
                }
                strSqlBuilder.append(String.format("insert into table_call_count values ('%s','%s','%s','%s',%d,%d,'%s')",
                        nowDate, dbName, tableName, operate, callcount, errcallcount, operateSql));
            }
            if (strSqlBuilder.length() > 0) {
                PGUtil.ExecuteNoQueryWithoutReturning(DbConfig.pg_url + DbConfig.DBNAME + "qx_data", DbConfig.pg_userName, DbConfig.pg_pwd, strSqlBuilder.toString());
            }
            flag = true;
        } catch (Exception ex) {
            flag = false;
        }
        return flag;
    }
}
